package com.xrj4j.car_news

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import com.google.gson.Gson
import com.xrj4j.car_news.adapter.LogoAdapter
import com.xrj4j.car_news.api.CarApi
import com.xrj4j.car_news.databinding.ActivityLogoBinding
import com.xrj4j.car_news.model.LogoItem
import com.xrj4j.car_news.model.ResultDto
import com.xrj4j.car_news.utils.RetrofitUtils
import com.xrj4j.car_news.utils.ToastUtils
import retrofit2.Call
import retrofit2.Response

class LogoActivity : AppCompatActivity(), View.OnClickListener {

    private val binding: ActivityLogoBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_logo)
    }
    private val dataList = mutableListOf<LogoItem>()
    private val adapter: LogoAdapter by lazy {
        LogoAdapter(this, dataList)
    }

    private val msg = "当前首字母:"
    private var letter = "A"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_logo)
        binding.adapter = adapter
        binding.name = msg + letter

        loadData()

        binding.logoBtn.setOnClickListener(this)
    }

    private fun loadData() {
        val carApi = RetrofitUtils.getApi(CarApi.baseUrl, CarApi::class.java)
        val call = carApi.getCarLogo(CarApi.key, letter)
        val ctx = this
        call.enqueue(object : retrofit2.Callback<ResultDto<LogoItem>> {
            override fun onResponse(
                call: Call<ResultDto<LogoItem>>,
                response: Response<ResultDto<LogoItem>>
            ) {
                ToastUtils.show(ctx, "获取数据成功")
                val result: ResultDto<LogoItem>? = response.body()
                adapter.addDataList(result?.result)
            }

            override fun onFailure(call: Call<ResultDto<LogoItem>>, t: Throwable) {
                ToastUtils.show(ctx, "获取数据失败")
            }
        })
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.logoBtn -> {
                val input = binding.logoEt.text.toString().trim().uppercase()
                if (TextUtils.isEmpty(input) || letter == input) return
                letter = input
                binding.name = msg + letter
                loadData()
            }
        }
    }
}